package hc.util;

import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.DataInputStream;
import java.io.File;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.sql.Timestamp;
import java.util.Properties;

import javax.swing.JOptionPane;

public class ResourceUtil {
	private final static Class starterClass = getStarterClass();
	
	public static String getTimeStamp(){
		final Timestamp timestamp = new Timestamp(System.currentTimeMillis());
		final StringBuffer timestampBuf = new StringBuffer(25);
		timestampBuf.append((timestamp.getYear() + 1900));
		final int month = (timestamp.getMonth() + 1);
		timestampBuf.append((month < 10?("0"+month):month));
		final int day = timestamp.getDate();
		timestampBuf.append(day < 10?("0"+day):day);
		final int hour = timestamp.getHours();
		timestampBuf.append("_");
		timestampBuf.append(hour < 10?("0"+hour):hour);
		final int minute = timestamp.getMinutes();
		timestampBuf.append((minute < 10?("0"+minute):minute));
		final int second = timestamp.getSeconds();
		timestampBuf.append((second < 10?("0"+second):second));
		
		return timestampBuf.toString();
	}
	
	private static Class getStarterClass(){
		try {
			return Class.forName("starter.Starter");
		} catch (ClassNotFoundException e) {
//			LogManager.err("Cant find Class : " + starterClass);
//			e.printStackTrace();
		}
		return null;
	}
	
	public static String toMD5(byte tmp[]){
		char hexDigits[] = {       // 用来将字节转换成 16 进制表示的字符
			     '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',  'e', 'f'};
		char str[] = new char[16 * 2];   // 每个字节用 16 进制表示的话，使用两个字符，
		int k = 0;                                // 表示转换结果中对应的字符位置
		for (int i = 0; i < 16; i++) {          // 从第一个字节开始，对 MD5 的每一个字节
		                                 // 转换成 16 进制字符的转换
			byte byte0 = tmp[i];                 // 取第 i 个字节
			str[k++] = hexDigits[byte0 >>> 4 & 0xf];  // 取字节中高 4 位的数字转换, 
		                                             // >>> 为逻辑右移，将符号位一起右移
			str[k++] = hexDigits[byte0 & 0xf];            // 取字节中低 4 位的数字转换
		} 
		return new String(str);                     
	}

	
	public static Object get(int id){
		if(id < 10000){
			return UILang.getUILang(id);
		}
		return null;
	}
	
	private static final ClassLoader cldr = ResourceUtil.class.getClassLoader();
	
	public static URL getResource(String fileName){
	    return cldr.getResource(fileName);
	}

	public static byte[] getAbsPathContent(String path) throws Exception{
		return getResource(getAbsPathInputStream(path));
	}
	
	public static DataInputStream getAbsPathInputStream(String path) throws Exception{
		URL uri = null;
		try{
			if(starterClass != null){
				uri = starterClass.getResource(path);
				return getInputStream(uri);
			}
		}catch (Exception e) {
		}
		
		try{
			return getInputStream(ResourceUtil.class.getResource(path));
		}catch (Exception e) {
		}
		
		uri = new File("." + path).toURI().toURL();
		return getInputStream(uri);
	}
	
	private static DataInputStream getInputStream(URL url) throws Exception {
		return new DataInputStream(url.openStream());
	}

	public static byte[] getResource(DataInputStream dataIs) throws Exception {
		byte[] imgDataBa = new byte[dataIs.available()];
//		DataInputStream dataIs = new DataInputStream(uri.openStream());
		dataIs.readFully(imgDataBa);
		dataIs.close();
		return imgDataBa;
	}

	public static synchronized String createResourceID(){
		String p_id = PropertiesManager.getValue(PropertiesManager.p_ResourceID);
		if(p_id == null){
			p_id = "1";
		}else{
			p_id = String.valueOf(Integer.parseInt(p_id) + 1);
		}
		PropertiesManager.setValue(PropertiesManager.p_ResourceID, p_id);
		PropertiesManager.saveFile();
		
		return p_id;
	}
	
	static {
		//初始时，要删除上次可能因停电产生的需要待删除的资源。
		notifyCancle();
	}
	
	public static void notifySave(){
		PropertiesManager.setValue(PropertiesManager.p_ResourcesMaybeUnusedNew, "");
		removeUnused(PropertiesManager.p_ResourcesMaybeUnusedOld);
		PropertiesManager.saveFile();
	}
	
	public static void notifyCancle() {
		PropertiesManager.setValue(PropertiesManager.p_ResourcesMaybeUnusedOld, "");
		removeUnused(PropertiesManager.p_ResourcesMaybeUnusedNew);
		PropertiesManager.saveFile();
	}

	private static void removeUnused(String pNew) {
		String rr = PropertiesManager.getValue(pNew);
		if(rr == null){
			return;
		}
		String baseDir = System.getProperty("user.dir");
		String[] toRemove = rr.split(";");
		for (int i = 0; i < toRemove.length; i++) {
			String url = toRemove[i];
			if(url.length() > 0){
				if(url.indexOf("hc/res/") >= 0){
					continue;
				}
				File file = new File(baseDir + url);
				//强制释放可能没有关闭的资源。
				System.gc();
				boolean b = file.delete();
				//强制释放可能没有关闭的资源。
				System.gc();
//				System.out.println("Del ico : " + file.toString() + ", succe:" + b);
			}
		}
		PropertiesManager.setValue(pNew, "");
		PropertiesManager.saveFile();
	}
	
	public static void addMaybeUnusedResource(String url, boolean isNew){
		String p = null;
		if(isNew){
			p = PropertiesManager.p_ResourcesMaybeUnusedNew;
		}else{
			p = PropertiesManager.p_ResourcesMaybeUnusedOld;
		}
		addUnused(url, p);
	}

	private static void addUnused(String url, String p_new) {
		String rr = PropertiesManager.getValue(p_new);
		if(rr == null){
			rr = "";
		}
		if(rr.length() == 0){
			rr = url;
		}else{
			rr += ";" + url;
		}
		PropertiesManager.setValue(p_new, rr);
		PropertiesManager.saveFile();
	}

	public static void loadJar(File jarfile) throws Exception{
		Method addPath = null;
	    addPath = URLClassLoader.class.getDeclaredMethod("addURL", new Class[] { URL.class });
	    addPath.setAccessible(true);
	
		URLClassLoader loader = (URLClassLoader) ClassLoader.getSystemClassLoader();
	
		addPath.invoke(loader, new Object[] { jarfile.toURI().toURL() });
	}

	public static BufferedImage resizeImage(final BufferedImage bufferedimage, final int w, final int h){
		int type = bufferedimage.getColorModel().getTransparency();        
		BufferedImage img;        
		Graphics2D graphics2d;        
		(graphics2d = (img = new BufferedImage(w, h, type)).createGraphics()).setRenderingHint(RenderingHints.KEY_INTERPOLATION,RenderingHints.VALUE_INTERPOLATION_BILINEAR);
		graphics2d.drawImage(bufferedimage, 0, 0, w, h, 0, 0, bufferedimage.getWidth(), bufferedimage.getHeight(), null);
		graphics2d.dispose();        
		return img;        
	}

	public static boolean isWindowsOS() {
		String os = System.getProperty("os.name");
		final boolean isWindow = os.toLowerCase().indexOf("windows") >= 0;
		return isWindow;
	}

	public static Properties loadThirdLibs() {
		final Properties thirdlibs = new Properties();
		try {
			String url = "http://homecenter.mobi/ajax/thirdlib.php";
			url = HttpUtil.replaceSimuURL(url, PropertiesManager.isTrue(PropertiesManager.p_IsSimu));
			thirdlibs.load(new URL(url).openStream());
		} catch (Exception e1) {
			JOptionPane.showMessageDialog(null, "Can NOT connect HomeCenter, please try after few seconds!", "Error Connect", JOptionPane.ERROR_MESSAGE);
			return null;
		}
		return thirdlibs;
	}
}
